package com.ysp.summary.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Data;

import java.net.InetSocketAddress;

/**
 * netty 客户端
 * @author Administrator
 */
@Data
public class NettyClient {

    /**
     * netty服务端主机和端口
     */
    private String host;
    private int port;

    public NettyClient(String host,int port){
        this.host = host;
        this.port = port;
    }

    public void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try{
            bootstrap.group(group)
                    .remoteAddress(new InetSocketAddress(host,port))
                    .channel(NioSocketChannel.class)
                    .handler(new NettyClientHandle());
            ChannelFuture future = bootstrap.connect().sync();
            future.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("Netty 客户端执行发生异常了："+e.getMessage());
        }finally{
            group.shutdownGracefully().sync();
        }
    }
}
